<template>
  <div class="proxies-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>代理管理</h2>
        <p>管理和配置代理服务器</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          添加代理
        </el-button>
      </div>
    </div>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="代理名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入代理名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="协议类型">
          <el-select v-model="searchForm.protocol" placeholder="请选择协议" clearable>
            <el-option label="HTTP" value="http" />
            <el-option label="HTTPS" value="https" />
            <el-option label="SOCKS5" value="socks5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="searchProxies">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 代理列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="filteredProxies"
        style="width: 100%"
      >
        <el-table-column prop="name" label="代理名称" header-align="center" min-width="150">
          <template #default="{ row }">
            <div class="proxy-name">
              <strong>{{ row.name }}</strong>
              <div class="proxy-description">{{ row.description || '暂无描述' }}</div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="host" label="地址" header-align="center" align="center" min-width="150">
          <template #default="{ row }">
            {{ row.host }}:{{ row.port }}
          </template>
        </el-table-column>
        
        <el-table-column prop="protocol" label="协议" header-align="center" align="center" width="100">
          <template #default="{ row }">
            <el-tag :type="getProtocolTagType(row.protocol)">
              {{ row.protocol.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="isAnonymous" label="匿名" header-align="center" align="center" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.isAnonymous" color="#67c23a"><CircleCheck /></el-icon>
            <el-icon v-else color="#f56c6c"><CircleClose /></el-icon>
          </template>
        </el-table-column>
        
        <el-table-column prop="auth" label="认证" header-align="center" align="center" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.auth" color="#409eff"><Lock /></el-icon>
            <el-icon v-else color="#909399"><Unlock /></el-icon>
          </template>
        </el-table-column>
        
        <el-table-column prop="loadBalance" label="负载均衡" header-align="center" align="center" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.loadBalance" size="small">
              {{ getLoadBalanceLabel(row.loadBalance) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="isActive" label="状态" header-align="center" align="center" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.isActive"
              @change="toggleProxyStatus(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="updatedAt" label="更新时间" header-align="center" align="center" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" header-align="center" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editProxy(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteProxy(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 创建/编辑代理对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="proxyFormRef"
        :model="proxyForm"
        :rules="proxyFormRules"
        label-width="100px"
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="代理名称" prop="name">
              <el-input v-model="proxyForm.name" placeholder="请输入代理名称" />
            </el-form-item>
          </el-col>
          
          <el-col :span="16">
            <el-form-item label="主机地址" prop="host">
              <el-input v-model="proxyForm.host" placeholder="IP地址或域名" />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="端口" prop="port">
              <el-input-number
                v-model="proxyForm.port"
                :min="1"
                :max="65535"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="协议类型" prop="protocol">
              <el-select v-model="proxyForm.protocol" style="width: 100%">
                <el-option label="HTTP" value="http" />
                <el-option label="HTTPS" value="https" />
                <el-option label="SOCKS5" value="socks5" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="负载均衡">
              <el-select v-model="proxyForm.loadBalance" style="width: 100%">
                <el-option label="轮询" value="round_robin" />
                <el-option label="最少连接" value="least_connections" />
                <el-option label="IP哈希" value="ip_hash" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item>
              <el-checkbox v-model="proxyForm.isAnonymous">高匿名代理</el-checkbox>
              <el-checkbox v-model="proxyForm.isActive">启用代理</el-checkbox>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item>
              <el-checkbox v-model="enableAuth" @change="handleAuthChange">启用认证</el-checkbox>
            </el-form-item>
          </el-col>
          
          <template v-if="enableAuth">
            <el-col :span="12">
              <el-form-item label="用户名" prop="auth.username">
                <el-input v-model="proxyForm.auth!.username" placeholder="认证用户名" />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="密码" prop="auth.password">
                <el-input
                  v-model="proxyForm.auth!.password"
                  type="password"
                  placeholder="认证密码"
                  show-password
                />
              </el-form-item>
            </el-col>
          </template>
          
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input
                v-model="proxyForm.description"
                type="textarea"
                :rows="3"
                placeholder="代理服务器描述（可选）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitProxy">
          {{ submitLoading ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  CircleCheck,
  CircleClose,
  Lock,
  Unlock
} from '@element-plus/icons-vue'
import { proxyApi } from '../api'
import { formatDateTime, isValidIP, isValidPort } from '../utils'
import type { ProxyConfig, ProxyForm } from '../types'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const proxyFormRef = ref<FormInstance>()
const currentProxy = ref<ProxyConfig | null>(null)
const enableAuth = ref(false)

const proxies = ref<ProxyConfig[]>([])

const searchForm = reactive({
  name: '',
  protocol: '',
  status: null as boolean | null
})

const proxyForm = reactive<ProxyForm>({
  name: '',
  host: '',
  port: 8080,
  protocol: 'http',
  isAnonymous: false,
  isActive: true,
  auth: {
    username: '',
    password: ''
  },
  loadBalance: 'round_robin',
  description: ''
})

// 计算属性
const dialogTitle = computed(() => {
  return currentProxy.value ? '编辑代理' : '添加代理'
})

const filteredProxies = computed(() => {
  let result = proxies.value
  
  if (searchForm.name) {
    result = result.filter(proxy => 
      proxy.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  if (searchForm.protocol) {
    result = result.filter(proxy => proxy.protocol === searchForm.protocol)
  }
  
  if (searchForm.status !== null) {
    result = result.filter(proxy => proxy.isActive === searchForm.status)
  }
  
  return result
})

// 表单验证规则
const proxyFormRules: FormRules = {
  name: [
    { required: true, message: '请输入代理名称', trigger: 'blur' }
  ],
  host: [
    { required: true, message: '请输入主机地址', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && !isValidIP(value) && !/^[a-zA-Z0-9.-]+$/.test(value)) {
          callback(new Error('请输入有效的IP地址或域名'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  port: [
    { required: true, message: '请输入端口号', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && !isValidPort(value)) {
          callback(new Error('端口号必须在1-65535之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  protocol: [
    { required: true, message: '请选择协议类型', trigger: 'change' }
  ],
  'auth.username': [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (enableAuth.value && !value) {
          callback(new Error('请输入认证用户名'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  'auth.password': [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (enableAuth.value && !value) {
          callback(new Error('请输入认证密码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 方法
const loadProxies = async () => {
  try {
    loading.value = true
    const response = await proxyApi.getProxies()
    
    if (response.code === 200) {
      proxies.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('Failed to load proxies:', error)
    ElMessage.error('加载代理列表失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  currentProxy.value = null
  resetForm()
  dialogVisible.value = true
}

const editProxy = (proxy: ProxyConfig) => {
  currentProxy.value = proxy
  Object.assign(proxyForm, {
    name: proxy.name,
    host: proxy.host,
    port: proxy.port,
    protocol: proxy.protocol,
    isAnonymous: proxy.isAnonymous,
    isActive: proxy.isActive,
    auth: proxy.auth ? { ...proxy.auth } : { username: '', password: '' },
    loadBalance: proxy.loadBalance,
    description: proxy.description || ''
  })
  
  enableAuth.value = !!proxy.auth
  dialogVisible.value = true
}

const deleteProxy = async (proxy: ProxyConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除代理 "${proxy.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await proxyApi.deleteProxy(proxy.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await loadProxies()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete proxy:', error)
      ElMessage.error('删除失败')
    }
  }
}

const toggleProxyStatus = async (proxy: ProxyConfig) => {
  try {
    const response = await proxyApi.toggleProxy(proxy.id, proxy.isActive)
    
    if (response.code === 200) {
      ElMessage.success(`代理已${proxy.isActive ? '启用' : '禁用'}`)
      // 更新本地数据
      const index = proxies.value.findIndex(p => p.id === proxy.id)
      if (index !== -1) {
        proxies.value[index] = response.data
      }
    } else {
      ElMessage.error(response.message)
      // 恢复原状态
      proxy.isActive = !proxy.isActive
    }
  } catch (error) {
    console.error('Failed to toggle proxy status:', error)
    ElMessage.error('操作失败')
    // 恢复原状态
    proxy.isActive = !proxy.isActive
  }
}

const submitProxy = async () => {
  if (!proxyFormRef.value) return
  
  try {
    const valid = await proxyFormRef.value.validate()
    if (!valid) return
    
    submitLoading.value = true
    
    const formData = { ...proxyForm }
    
    // 如果未启用认证，清空认证信息
    if (!enableAuth.value) {
      delete formData.auth
    }
    
    let response
    if (currentProxy.value) {
      // 编辑
      response = await proxyApi.updateProxy(currentProxy.value.id, formData)
    } else {
      // 创建
      response = await proxyApi.createProxy(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(currentProxy.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      await loadProxies()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('Failed to save proxy:', error)
    ElMessage.error('保存失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.assign(proxyForm, {
    name: '',
    host: '',
    port: 8080,
    protocol: 'http',
    isAnonymous: false,
    isActive: true,
    auth: {
      username: '',
      password: ''
    },
    loadBalance: 'round_robin',
    description: ''
  })
  
  enableAuth.value = false
  
  if (proxyFormRef.value) {
    proxyFormRef.value.clearValidate()
  }
}

const handleAuthChange = (enabled: boolean) => {
  if (!enabled) {
    proxyForm.auth = {
      username: '',
      password: ''
    }
  }
}

const searchProxies = () => {
  // 过滤已在computed中处理
}

const resetSearch = () => {
  searchForm.name = ''
  searchForm.protocol = ''
  searchForm.status = null
}

const getProtocolTagType = (protocol: string) => {
  const typeMap: { [key: string]: string } = {
    http: 'primary',
    https: 'success',
    socks5: 'warning'
  }
  return typeMap[protocol] || 'info'
}

const getLoadBalanceLabel = (loadBalance: string) => {
  const labelMap: { [key: string]: string } = {
    round_robin: '轮询',
    least_connections: '最少连接',
    ip_hash: 'IP哈希'
  }
  return labelMap[loadBalance] || loadBalance
}

// 生命周期
onMounted(() => {
  loadProxies()
})
</script>

<style scoped>
.proxies-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-title h2 {
  margin: 0 0 4px 0;
  font-size: 24px;
  color: #2c3e50;
}

.page-title p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 24px;
}

.table-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.proxy-name {
  line-height: 1.4;
}

.proxy-description {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .page-actions {
    width: 100%;
  }
  
  .page-actions .el-button {
    width: 100%;
  }
}
</style>